<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require dirname(__FILE__).'/pc_controller.php';

require_once dirname(__FILE__).'/menu.php';

class Honda_customer extends PC_controller {

    public function __construct(){
        parent::__construct();
        $this->load->model('Hondacustomermodel','m_customer');
    }

    public function index(){
        $data = parent::index();

        global $g_honda_game_gift,$g_honda_reservation_type,$g_honda_card_type,$g_honda_gift_status;
        $data['game_gift'] = array4js($g_honda_game_gift);
        $data['reservation_type'] = array4js($g_honda_reservation_type);
        $data['card_type'] = array4js($g_honda_card_type);
        $data['gift_status'] = array4js($g_honda_gift_status);

        $this->load->view('admin/honda_customer',$data);
    }

    public function getCustomerList(){
        $info = $this->input->post();
        $assist['where'] = getFilter($this->input->post(),Hondacustomermodel::$searchField);
        $assist['like'] = getFilter($this->input->post(),Hondacustomermodel::$likeField);
        $assist['sort'] = getSort($this->input->post(),Hondacustomermodel::$sortField);
        $assist['pagination'] = getPagination($this->input->post());

        if(isset($info['gift_status']) && $info['gift_status'] == 0) {
            $assist['where']['honda_customer.gift_type >'] ='0';
        }

        if(isset($assist['where']['honda_customer.gift_type']) && $assist['where']['honda_customer.gift_type'] < 0) {
            unset($assist['where']['honda_customer.gift_type']);
            $assist['where']['honda_customer.gift_type >'] ='0';
        }
        if(isset($info['card_type'])) {
            $sql = '';
            if(isset($info['card_time_create_start'])) {
                $sql .= ' and card_time_create >= "'.$info['card_time_create_start'].'"';
            }
            if(isset($info['card_time_create_end'])) {
                $sql .= ' and card_time_create <= "'.$info['card_time_create_end'].'"';
            }
            if($info['card_type'] == 0) {
                $assist['where_sql'] = 'NOT EXISTS (select distinct customer_id from mpc_honda_card where {PRE}honda_customer.customer_id = {PRE}honda_card.customer_id'.$sql.')';
            } else if($info['card_type'] == -1) {
                // $this->db->join('honda_card','honda_customer.customer_id = honda_card.customer_id','right');
                $assist['where_sql'] = 'EXISTS (select distinct customer_id from mpc_honda_card where {PRE}honda_customer.customer_id = {PRE}honda_card.customer_id'.$sql.')';
            } else {
                // $assist['where_sql'] = 'customer_id in (select customer_id from mpc_honda_card )';
                $this->db->join('honda_card','honda_customer.customer_id = honda_card.customer_id','left');
                $this->db->where('card_type',$info['card_type']);
                if(isset($info['card_time_create_start'])) {
                    $this->db->where('card_time_create >=',$info['card_time_create_start']);
                }
                if(isset($info['card_time_create_end'])) {
                    $this->db->where('card_time_create <=',$info['card_time_create_end']);
                }
            }
        } else if(isset($info['card_time_create_start']) || isset($info['card_time_create_end'])) {
            $sql = '';
            if(isset($info['card_time_create_start'])) {
                $sql .= ' and card_time_create >= "'.$info['card_time_create_start'].'"';
            }
            if(isset($info['card_time_create_end'])) {
                $sql .= ' and card_time_create <= "'.$info['card_time_create_end'].'"';
            }
            $assist['where_sql'] = 'EXISTS (select distinct customer_id from mpc_honda_card where {PRE}honda_customer.customer_id = {PRE}honda_card.customer_id'.$sql.')';
        }
        list($list,$count) = $this->m_customer->getCustomerListSection($assist);
        // var_dump($this->db->last_query());
        $customer_ids = extractColumn($list,'customer_id');
        $card_list = $this->m_customer->getCardList($customer_ids);
        $card_list = spreadArray($card_list,'customer_id');

        foreach ($list as $key => $value) {
            $list[$key]['nickname'] = urldecode($value['nickname']);
            $list[$key]['card_list'] = isset($card_list[$value['customer_id']]) ? $card_list[$value['customer_id']] : array();
        }

        $this->response->setSuccess();
        $this->response->setItems($list);
        $this->response->setTotalCount($count);
        $this->response->responseExit();
    }

    public function exportCustomerList() {
        @set_time_limit(0);
        @ini_set('memory_limit', '3048M');

        $info = $this->input->get();
        $assist['where'] = getFilter($this->input->get(),Hondacustomermodel::$searchField);
        $assist['like'] = getFilter($this->input->get(),Hondacustomermodel::$likeField);
        $assist['sort'] = getSort($this->input->get(),Hondacustomermodel::$sortField);

        if(isset($assist['where']['honda_customer.gift_type']) && $assist['where']['honda_customer.gift_type'] < 0) {
            unset($assist['where']['honda_customer.gift_type']);
            $assist['where']['honda_customer.gift_type >'] ='0';
        }

        $this->load->library('excel');
        $this->excel->init('广汽本田游戏用户_'.date('YmdH').'.xls');
        $this->excel->addSheet('广汽本田游戏用户');
        $this->excel->addTitle(array(
            array('content'=>'ID'),
            array('content'=>'奖品'),
            array('content'=>'openid'),
            array('content'=>'抽奖次数'),
            array('content'=>'创建时间'),
            array('content'=>'获奖时间'),
            array('content'=>'姓名'),
            array('content'=>'手机'),
            array('content'=>'卡券类型'),
            array('content'=>'卡券号'),
            array('content'=>'卡券时间'),
            array('content'=>'预约店面'),
            array('content'=>'预约店面编码'),
            array('content'=>'预约类型'),
            array('content'=>'预约省份'),
            array('content'=>'预约城市'),
            array('content'=>'预约店面'),
        ));
        
        if(isset($info['gift_status']) && $info['gift_status'] == 0) {
            $assist['where']['honda_customer.gift_type >'] ='0';
        }

        if(isset($info['card_type'])) {
            $sql = '';
            if(isset($info['card_time_create_start'])) {
                $sql .= ' and card_time_create >= "'.$info['card_time_create_start'].'"';
            }
            if(isset($info['card_time_create_end'])) {
                $sql .= ' and card_time_create <= "'.$info['card_time_create_end'].'"';
            }
            if($info['card_type'] == 0) {
                $assist['where_sql'] = 'NOT EXISTS (select distinct customer_id from mpc_honda_card where {PRE}honda_customer.customer_id = {PRE}honda_card.customer_id'.$sql.')';
            } else if($info['card_type'] == -1) {
                // $this->db->join('honda_card','honda_customer.customer_id = honda_card.customer_id','right');
                $assist['where_sql'] = 'EXISTS (select distinct customer_id from mpc_honda_card where {PRE}honda_customer.customer_id = {PRE}honda_card.customer_id'.$sql.')';
            } else {
                // $assist['where_sql'] = 'customer_id in (select customer_id from mpc_honda_card )';
                $this->db->join('honda_card','honda_customer.customer_id = honda_card.customer_id','left');
                $this->db->where('card_type',$info['card_type']);
                if(isset($info['card_time_create_start'])) {
                    $this->db->where('card_time_create >=',$info['card_time_create_start']);
                }
                if(isset($info['card_time_create_end'])) {
                    $this->db->where('card_time_create <=',$info['card_time_create_end']);
                }
            }
        } else if(isset($info['card_time_create_start']) || isset($info['card_time_create_end'])) {
            $sql = '';
            if(isset($info['card_time_create_start'])) {
                $sql .= ' and card_time_create >= "'.$info['card_time_create_start'].'"';
            }
            if(isset($info['card_time_create_end'])) {
                $sql .= ' and card_time_create <= "'.$info['card_time_create_end'].'"';
            }
            $assist['where_sql'] = 'EXISTS (select distinct customer_id from mpc_honda_card where {PRE}honda_customer.customer_id = {PRE}honda_card.customer_id'.$sql.')';
        }
        list($list,$count) = $this->m_customer->getCustomerListSection($assist);
        if(count($list) > 30000) {
            die('导出数据太大，请筛选数据导出!');
        }

        $card_list = $this->m_customer->getCardList();
        $card_list = spreadArray($card_list,'customer_id');

        // foreach ($list as $key => $value) {
        //     $list[$key]['nickname'] = urldecode($value['nickname']);
        //     $list[$key]['card_list'] = isset($card_list[$value['customer_id']]) ? $card_list[$value['customer_id']] : array();
        // }

        global $g_honda_game_gift,$g_honda_card_type;

        $sex_array = array(
            0 => '未知',
            1 => '男',
            2 => '女',
        );
        $reservation_type_arr = array(
        	'1' => '双快',
        	'2' => '车主讲堂',
        );
        foreach ($list as $key => $value) {
            $value['nickname'] = urldecode($value['nickname']);
            $gift_info = array();

            $one_card = isset($card_list[$value['customer_id']]) ? $card_list[$value['customer_id']] : array();
            $card_type_arr = array();
            $card_number_arr = array();
            $card_time_create_arr = array();
            foreach($one_card as $k1 => $v1) {
                $card_type_arr[] = id2name($v1['card_type'],$g_honda_card_type);
                $card_number_arr[] = $v1['card_number'];
                $card_time_create_arr[] = $v1['card_time_create'];
            }

            $this->excel->addRow(array(
                array('content' => $value['customer_id']),
                array('content' => id2name($value['gift_type'],$g_honda_game_gift)),
                array('content' => $value['openid']),
                array('content' => $value['lottery_times']),
                array('content' => $value['customer_time_create']),
                array('content' => $value['customer_time_lottery']),
                array('content' => $value['customer_name']),
                array('content' => $value['customer_phone']),
                array('content' => implode(',', $card_type_arr)),
                array('content' => implode(',', $card_number_arr)),
                array('content' => implode(',', $card_time_create_arr)),
                array('content' => $value['user_name']),
                array('content' => $value['user_code']),
                array('content' => id2name($value['customer_reservation_type'],$reservation_type_arr)),
            ));
            unset($card_list[$value['customer_id']]);
            unset($list[$key]);
        }

        $this->excel->freezePanes(1,0);
        $this->excel->generate();
    }

    public function disableCustomer() {
        $this->validate->setRule('customer_id','integer');
        $this->validate->setRule('customer_id','message',$this->lang->line('error_parameter'));
        if(!$this->validate->run($this->input->post())){
            $this->response->setDetail($this->validate->getMessage());
            $this->response->responseExit();
        }
        $info = $this->validate->getResult();

        $info['customer_status'] = STATUS_DELETE;
        $this->m_customer->editCustomer($info);

        $this->response->setSuccess();
        $this->response->setDetail('更新成功!');
        $this->response->responseExit();
    }

    public function enableCustomer() {
        $this->validate->setRule('customer_id','integer');
        $this->validate->setRule('customer_id','message',$this->lang->line('error_parameter'));
        if(!$this->validate->run($this->input->post())){
            $this->response->setDetail($this->validate->getMessage());
            $this->response->responseExit();
        }
        $info = $this->validate->getResult();

        $info['customer_status'] = STATUS_DISABLE;
        $this->m_customer->editCustomer($info);

        $this->response->setSuccess();
        $this->response->setDetail('更新成功!');
        $this->response->responseExit();
    }

    public function importList() {
        $this->validate->setRule('type','integer');
        $this->validate->setRule('file','file');
        $this->validate->setRule('file','message',$this->lang->line('error_parameter'));
        if(!$this->validate->run($this->input->post())){
            $this->response->setDetail($this->validate->getMessage());
            $this->response->responseExit();
        }
        $info = $this->validate->getResult();

        $this->load->library('zmexcel');
        $this->zmexcel->checkExcelFile($info['file']);
        $path = $this->m_app->saveFile($info['file'],array(),UPLOAD_PATH_FILE);
        $this->zmexcel->init(UPLOAD_PATH_FILE.$path);

        @set_time_limit(0);
        @ini_set('memory_limit', '3048M');
        $data = $this->zmexcel->getDatas();

        $this->load->database();
        $assist = array(
            'where' => array('honda_customer.gift_type' => 1,'honda_customer.gift_status !=' => 1,'customer_phone !=' => ''),
        );
        list($list,$count) = $this->m_customer->getCustomerListSection($assist);
        $list = spreadArray($list,'customer_phone');

        list($history_list,$count) = $this->m_customer->getLotteryHistoryListSection(array(
            'where' => array('honda_lottery_history.gift_type' => 1,'honda_lottery_history.gift_status !=' => 1),
            'nojoin' => true,
        ));
        $history_list = reindexArray($history_list,'customer_id');

        $update_customer_arr = array();
        $update_history_arr = array();
        $gift_status_arr = array(
            '成功' => 1,
            '充值中' => -1,
            '失败' => -2,
        );

        $existed = array();
        // $type_arr = array_flip($g_honda_code_type);
        foreach ($data as $k => $record) {
            foreach($record as $key => $value) {
                if(!$value || $value==null) $record[$key] = '';
                $record[$key] = trim($record[$key]);
            }
            $k += 2;
            $customer_phone = $record['B'];
            if($customer_phone == '') continue;
            // if(isset($existed[$customer_phone])) {
            //     $this->response->setDetail("第{$k}行列表存在相同的手机号[{$customer_phone}]!!!");
            //     $this->response->responseExit();
            // }
          //   if(!isset($type_arr[$record['A']])) {
          //    $this->response->setDetail("第{$k}行列表[{$record['A']}]不存在!!!");
                // $this->response->responseExit();
          //   }
            if(!isset($list[$customer_phone])) {
                if($record['G'] == '成功') continue; //已成功的，就不覆盖了!
                $this->response->setDetail("第{$k}行列表存在的手机号[{$customer_phone}]未中奖，请确认!!!");
                $this->response->responseExit();
            }

            if(!isset($gift_status_arr[$record['G']])) {
                $this->response->setDetail("第{$k}行列表存在的充值状态[{$record['G']}]不对,请确保状态为 成功、充值中、失败!!!");
                $this->response->responseExit();
            }


            $lottery_time_time_active = empty($record['K']) ? $record['J'] : $record['K'];
            if(empty($lottery_time_time_active)) {
                $this->response->setDetail("第{$k}行列表存在的充值时间不能为空!!!".$lottery_time_time_active);
                $this->response->responseExit();
            }

            if(isset($existed[$customer_phone]) && $existed[$customer_phone] > $lottery_time_time_active) {
                continue;
            }
            foreach ($list[$customer_phone] as $k1 => $v1) {
                
                $update_customer_arr[] = array(
                    'customer_id' => $v1['customer_id'],
                    'gift_status' => $gift_status_arr[$record['G']],
                );
                if(!isset($history_list[$v1['customer_id']])) {
                    $this->response->setDetail("第{$k}行列表存在的手机号[{$customer_phone}]未中奖，请确认!");
                    $this->response->responseExit();
                }
                $update_history_arr[] = array(
                    'lottery_history_id' => $history_list[$v1['customer_id']]['lottery_history_id'],
                    'gift_status' => $gift_status_arr[$record['G']],
                    'gift_remark' => $record['I'],
                    'lottery_time_time_active' => $lottery_time_time_active,
                );
            }
            $existed[$customer_phone] = $lottery_time_time_active;
        }
        $update_customer_arr = array_values($update_customer_arr);
        $update_history_arr = array_values($update_history_arr);
        $this->m_customer->updateCustomerBatch($update_customer_arr);
        $this->m_customer->updateLotteryHistoryBatch($update_history_arr);
        $this->db->close();

        $this->response->setSuccess();
        $this->response->setDetail($this->lang->line('success_update'));
        $this->response->responseExit();
    }
}
/* End of file customer.php */
/* Location: ./application/controllers/customer.php */